package cn.edu.dutir.model.vsm;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.Map;

import com.aliasi.util.AbstractExternalizable;
import com.aliasi.util.Compilable;

public class Document implements Compilable, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8739877501043856207L;
	String mDocId;
	String mText;
	Map<String, ? extends Number> mTermFrequency;

	public Document(String docId, Map<String, ? extends Number> termFrequency) {
		this(docId, null, termFrequency);
	}

	public Document(String docId, String text,
			Map<String, ? extends Number> termFrequency) {
		mDocId = docId;
		mText = text;
		mTermFrequency = termFrequency;
	}

	public String id(){
		return mDocId;
	}
	
	public Map<String, ? extends Number> termFrequency() {
		return mTermFrequency;
	}
	
    private Object writeReplace() {
        return new Externalizer(this);
    }
        
	@Override
	public void compileTo(ObjectOutput objOut) throws IOException {
		objOut.writeObject(new Externalizer(this));
	}

	private static class Externalizer extends AbstractExternalizable {
		final Document mDocument;
		public Externalizer() {
			this(null);
		}
		public Externalizer(Document doc) {
			mDocument = doc;
		}
		
		@SuppressWarnings("unchecked")
		@Override
		protected Object read(ObjectInput in) throws ClassNotFoundException,
				IOException {
			String docId = in.readUTF();
			Map<String, ? extends Number> featureMap = (Map<String, ? extends Number>) in
					.readObject();
			return new Document(docId, featureMap);
		}

		@Override
		public void writeExternal(ObjectOutput out) throws IOException {
			out.writeUTF(mDocument.mDocId);
			out.writeObject(mDocument.mTermFrequency);
		}
	}
}
